//@author A0105543N
#include "Helper.h"

bool Helper::checkDate(string date)
{
		int len = date.length();
		if (len != 8){
			cout << "Date should be in the form of yyyymmdd.";
			return false;}
	
			for (int i = 0;i < len;i ++)
			if (!isdigit(date[i])) {
				cout << "Date should be in the form of yyyymmdd.";
				return false;
			}
		ostringstream outstr;
		time_t currentTime;
		time (&currentTime);
		struct tm * today= localtime(&currentTime);   //the current time
		string todayString;
		outstr << (today -> tm_year + 1900) * 10000 + (today -> tm_mon + 1) * 100 + today -> tm_mday;
		todayString = outstr.str();
		if (date > todayString) {   //compare it with today
			cout << "Date shouldn't be later than today.";
			return false;
		}
		int year = 1000 * (date[0] - '0') + 100 * (date[1] - '0') + 10 * (date[2] - '0') + date[3] - '0';
		int mon = 10 * (date[4] - '0') + date[5] - '0';      //check month
			if ( mon > 12 || mon == 0 ) {
			cout << "Month should be an integer between 1 and 12.";
			return false;
			}
		int day = (date[6] -  '0') * 10 + date[7] - '0';  //check day
		if (day < 1 || day > 31) {
			cout << "Date input is not valid.";
			return false; }
		if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
			if (day == 31)
				{cout << "There are only 30 days in this month.";
			return false;}
		}
		else if (mon == 2){
		if (date[2] == '0' && date[3] == '0'){
			if (year % 400 == 0) {
				if (day > 29) {
					cout << "There are only 29 days in this month.";
					return false;}
			}
			else if (day > 28){
				cout << "There are only 28 days in this month.";
				return false;}
		}
		if (year % 4 == 0 && day > 29) {
			cout << "There are only 29 days in this month.";
			return false;}
		else if (year % 4 != 0 && day > 28){
			cout << "There are only 28 days in this month.";
			return false;
		}
		}
		return true;
}

string Helper::dayString(string date) {
	
	ostringstream daystring;

	int mon = 10 * (date[4] - '0') + date[5] - '0';
	int day = (date[6] -  '0') * 10 + date[7] - '0';
	int year = 1000 * (date[0] - '0') + 100 * (date[1] - '0') + 10 * (date[2] - '0') + date[3] - '0';
	daystring << year << ' ' << m_months[mon] << ' ' << setfill('0') << setw(2) << day;
	return(daystring.str());
}